<template>
  <el-container>
    <!-- #region 菜单 -->
    <el-aside width="200">
      <el-menu
        :collapse="isCollapse"
        active-text-color="#ffd04b"
        background-color="#545c64"
        class="el-menu-vertical-demo"
        :default-active="activeMenuItemPath"
        text-color="#fff"
        :collapse-transition="true"
        :router="true"
        unique-opened
      >
        <div class="row jcc aic" style="height: 50px">
          <img src="../assets/logo.svg" alt="logo" class="logo" />
        </div>
        <el-menu-item index="欢迎" :route="{ name: '欢迎' }">
          <el-icon>
            <home-filled />
          </el-icon>
          <span>首页</span>
        </el-menu-item>

        <template v-for="(menu, index) in store.user.state.menus" :key="index">
          <template v-if="menu.children?.length">
            <SubMenu :menu="menu"></SubMenu>
          </template>

          <template v-else>
            <el-menu-item :index="menu.name" :route="menu">
              <el-icon>
                <component :is="menu.meta?.icon" />
              </el-icon>
              <span>{{ menu.name }}</span>
            </el-menu-item>
          </template>
          <!-- <el-sub-menu v-else-if="menu.meta?.isMenu" :index="menu.path">
            <template #title>
              <el-icon>
                <component :is="menu.meta?.icon" />
              </el-icon>
              <span>{{ menu.name }}</span>
            </template>

            <template v-for="item in menu.children" :key="item.path">
              <template v-if="item?.children?.length > 0 && item.meta?.isMenu">
                <el-sub-menu :index="item.path">
                  <template #title>
                    <span>{{ item.name }}</span>
                  </template>
                  <template v-for="item2 in item.children" :key="item2.name">
                    <el-menu-item
                      v-if="item2.meta?.isMenu"
                      :index="`/${menu.path}/${item.path}/${item2.path}`"
                    >
                      {{ item2.name }}
                    </el-menu-item>
                  </template>
                </el-sub-menu>
              </template>
              <el-menu-item
                v-else-if="item.meta?.isMenu"
                :index="'/' + menu.path + '/' + item.path"
                :route="item"
              >
                {{ item.name }}
              </el-menu-item>
            </template>
          </el-sub-menu> -->
        </template>
      </el-menu>
    </el-aside>
    <!-- #endregion -->

    <el-container class="right-container">
      <el-header class="row jcsb aic">
        <div class="row aic">
          <el-tooltip
            class="box-item"
            effect="dark"
            :content="`${isCollapse ? '展开' : '收起'}左侧菜单`"
            placement="bottom"
          >
            <el-icon size="1.5rem" @click="isCollapse = !isCollapse">
              <Expand v-show="isCollapse" />
              <Fold v-show="!isCollapse" />
            </el-icon>
          </el-tooltip>
          <el-breadcrumb class="ml-1" :separator-icon="ArrowRight">
            <template v-for="item in route.matched" :key="item.name">
              <template v-if="item.path == '/'"></template>
              <el-breadcrumb-item v-else :to="item.path">
                {{ item.name }}
              </el-breadcrumb-item>
            </template>
          </el-breadcrumb>
        </div>
        <!-- <CurrentTime class="mr-1" /> -->
        <div class="row aic">
          <ToggleFullScreen />
          <el-icon size="1.5rem" class="mr-1">
            <TranslateIcon />
          </el-icon>
          <UserDropdown />
        </div>
      </el-header>

      <nav class="tags row">
        <el-tag
          v-for="(tag, index) in openTags"
          :key="index"
          closable
          :type="`${tag.name == activeMenuItemPath ? '' : 'info'}`"
          :disable-transitions="false"
          @click="onTagClick(tag.name)"
          @close="handleClose(tag.name)"
        >
          {{ tag.name }}
        </el-tag>
      </nav>

      <el-main>
        <router-view v-slot="{ Component }" v-if="isRouterAlive">
          <Suspense>
            <transition name="slide-fade" mode="out-in">
              <div :key="(Component as any)" class="h100">
                <component :is="Component" style="height: 100%" />
              </div>
            </transition>
          </Suspense>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
import SubMenu from '@/components/Menus/SubMenu.vue';
import { nextTick, onMounted, ref, provide } from 'vue';
import TranslateIcon from '@/components/icons/TranslateIcon.vue';
import CurrentTime from '@/components/CurrentTime.vue';
import { ArrowRight } from '@element-plus/icons-vue';

import { onBeforeRouteUpdate, RouteRecordName, useRoute } from 'vue-router';
import router from '@/route';
import ToggleFullScreen from '@/components/ToggleFullScreen.vue';
import UserDropdown from '@/components/UserDropdown/index.vue';
import { shios } from '@/api/Shios';
import { store } from '@/store';

const isRouterAlive = ref(true);

/**
 * 刷新
 */
function reload() {
  isRouterAlive.value = false;
  nextTick(() => {
    isRouterAlive.value = true;
  });
}
provide('reload', reload);

const isCollapse = ref(false);
// const sessionMenus: Menu[] = JSON.parse(
//   sessionStorage.getItem('menus') ?? '[]'
// );

store.user.state.menus;
onMounted(async () => {
  if (!store.user.state.menus?.length) {
    const res = await shios.get<Menu[]>('menus');
    console.log(res);
    if (res.data) {
      // store.user.state.menus = res.data;
      store.user.updateMenus(res.data);
      //  sessionStorage.setItem('menus', JSON.stringify(res.data));
    }
  }
});

const route = useRoute();
const activeMenuItemPath = ref('');
if (route.name) {
  activeMenuItemPath.value = route.name.toString();
  console.log(activeMenuItemPath.value);
}

const openTags = ref<
  {
    name: RouteRecordName | null | undefined;
  }[]
>([
  {
    name: route.name,
  },
]);
// function onMenuItem(e: MenuItemRegistered) {
//   console.log(e);
//   router.replace({ name: e.index });
// }
/** 路由更新之前的回调*/
onBeforeRouteUpdate((to) => {
  // 仅当 id 更改时才获取用户，例如仅 query 或 hash 值已更改
  const tabs = openTags.value;
  const tab = tabs.find((v) => v.name === to.name);
  if (!tab) {
    addTab(to.fullPath.toLowerCase(), to.name?.toString() || '首页');
  }
  if (to.name) {
    activeMenuItemPath.value = to.name.toString();
  }
  // breadcrumbs.value = to.matched;

  //  await nextTick();
});
/**
 * 添加选项卡
 * @param index
 * @param targetName
 */
const addTab = (index: string, targetName: string) => {
  // const newTabName = targetName;

  openTags.value.push({
    name: targetName,
  });
  if (openTags.value.length > 7) {
    openTags.value.shift();
  }
};
/**
 *
 * @param  name
 */
function onTagClick(name: RouteRecordName | null | undefined) {
  if (name) {
    router.replace({ name });
  }
}

/**
 * 关闭选项卡
 * @param {string}targetName
 */
function handleClose(targetName: RouteRecordName | null | undefined) {
  if (!targetName) {
    return;
  }
  const tabs = openTags.value;
  let activeName = activeMenuItemPath.value;
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab?.name) {
          activeName = nextTab.name.toString();
        }
      }
    });
  }

  activeMenuItemPath.value = activeName;
  openTags.value = tabs.filter((tab) => tab.name !== targetName);
}
</script>

<style scoped lang="scss">
.el-container {
  height: 100%;
}

.right-container {
  background-color: #f0f0f0;
}

.el-menu {
  border-right: none;

  .logo {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #fff;
    padding: 4px;
    box-sizing: border-box;
  }
}

.el-menu:not(.el-menu--collapse) {
  width: 200px;
  height: 100%;
}

.el-header {
  position: relative;
  background-color: white;
  height: 50px;

  // background-color: var(--el-color-primary-light-7);
  // color: var(--el-text-color-primary);
  .el-icon {
    cursor: pointer;

    :active {
      border: 2px solid rgba(0, 102, 255, 0.1);
      background-color: rgba(0, 102, 255, 0.1);
    }
  }

  .el-dropdown-link {
    cursor: pointer;
    display: flex;
    align-items: center;

    .el-icon {
      color: var(--el-color-primary);
    }
  }
}

.el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}

.tags {
  margin: 1ex 1rem;

  .el-tag {
    cursor: pointer;

    + .el-tag {
      margin-left: 1ex;
    }
  }
}

.el-main {
  padding: 0;
  margin: 0 1em 1em;
  padding: 1rem;
  border-radius: 6px;
  background-color: white;
  overflow: hidden;
}

/*
  Enter and leave animations can use different
  durations and timing functions.
*/
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.5s ease;
}

.slide-fade-enter-from {
  transform: translateX(-20px);
  opacity: 0;
  display: none;
}
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>
